package com.ty.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ty.bean.SaleOrder;
import com.ty.bean.SaleOrderContract;
import com.ty.bean.UserInfo;
import com.ty.common.crud.BaseServiceImpl;
import com.ty.common.utils.Assert;
import com.ty.context.UserContext;
import com.ty.mapper.*;
import com.ty.service.SaleOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SaleOrderServiceImpl extends BaseServiceImpl<SaleOrder, SaleOrderMapper> implements SaleOrderService {


    @Autowired
    CustomerInquiryMapper customerInquiryMapper;

    @Autowired
    SaleOrderDetailMapper saleOrderDetailMapper;

    @Autowired
    SaleOrderContractMapper saleOrderContractMapper;

    @Autowired
    SaleOrderProductMapper saleOrderProductMapper;

    @Transactional
    @Override
    public int save(SaleOrder entity) {

        //获取用户信息
        UserInfo info = UserContext.get();
        entity.setSalesId(info.getId());
        UserContext.clear();

        //订单编号 自动生产
        String sn = "XSDD2025020001";
        entity.setSn(sn);

        //判断有没有客户询价单号
        if (StrUtil.isEmpty(entity.getCustomerInquirySn())) {
            //根据客户id查询最近的 询价单编号
            entity.setCustomerInquirySn(customerInquiryMapper.queryLatestCode(entity.getCustomerId()));
        }

        //提成 计算    利润计算
        //保存销售订单
        int rs = super.save(entity);
        Assert.isZero(rs, "销售订单保存失败");

        //保存订单  技术要求细节
        if (null != entity.getSaleOrderDetail()) {
            entity.getSaleOrderDetail().setRelationSn(sn);
            rs = saleOrderDetailMapper.save(entity.getSaleOrderDetail());
            Assert.isZero(rs, "保存销售订单技术细节要求 失败");
        }

        //保存合同
        if (null != entity.getSaleOrderContract()) {
            entity.getSaleOrderContract().setRelationSn(sn);
            rs = saleOrderContractMapper.save(entity.getSaleOrderContract());
            Assert.isZero(rs, "保存销售订单合同失败");
        }


        //保存产品
        if (null != entity.getSaleOrderProductList() && entity.getSaleOrderProductList().size() > 0) {
            rs = saleOrderProductMapper.batchSave(sn, entity.getSaleOrderProductList());
            Assert.isZero(rs, "保存销售订单产品失败");
        }


        return 1;
    }
}
